import axios from 'axios';
import { Message } from 'element-ui';
// let baseURL = 'http://192.168.4.168:5000' //本地接口地址
let baseURL = 'http://47.111.90.123:5000' //服务器接口地址
// 登录请求方法
const loginreq = (method, url, params) => {
	return new Promise((resolve,reject)=>{
		axios({
		    method: method,
		    url: baseURL + url,
		    headers: {
		        'Content-Type': 'application/x-www-form-urlencoded',
		    },
		    data: params,
		    traditional: true,
		    transformRequest: [
		        function(data) {
		            let ret = ''
		            for (let it in data) {
		                ret +=
		                    encodeURIComponent(it) +
		                    '=' +
		                    encodeURIComponent(data[it]) +
		                    '&'
		            }
		            return ret
		        }
		    ]
		}).then(res => {
			if(res.data.state===200){
				resolve(res.data);
			}else{
				Message.error({
					message:res.data.message
				})
				reject(res.data)
			}
		}).catch(err=>{
			Message.error({
				message:'服务端异常'
			})
			reject(err.data)
		});
	})
};
// 通用公用方法
const req = (method, url, params) => {
	params.token=localStorage.getItem('logintoken');
	return new Promise((resolve,reject)=>{
		axios({
		    method: method,
		    url: baseURL + url,
		    headers: {
		        'Content-Type': 'application/x-www-form-urlencoded',
		        token: localStorage.getItem('logintoken')
		    },
		    data: params,
		    traditional: true,
		    transformRequest: [
		        function(data) {
		            let ret = ''
		            for (let it in data) {
		                ret +=
		                    encodeURIComponent(it) +
		                    '=' +
		                    encodeURIComponent(data[it]) +
		                    '&'
		            }
		            return ret
		        }
		    ]
		}).then(res => {
			if(res.data.state===200){
				resolve(res.data);
			}else{
				Message.error({
					message:res.data.message
				})
				reject(res.data)
			}
		}).catch(err=>{
			Message.error({
				message:'服务端异常'
			})
			reject(err.data)
		});
	})
};
// 上传图片方法
const upload = (method, url, params) => {
	params.token=localStorage.getItem('logintoken');
	return new Promise((resolve,reject)=>{
		axios({
		    method: method,
		    url: baseURL + url,
		    headers: {
		        token: localStorage.getItem('logintoken')
		    },
		    data: params
		}).then(res => {
			if(res.data.state===200){
				resolve(res.data);
			}else{
				Message.error({
					message:res.data.message
				})
				reject(res.data)
			}
		}).catch(err=>{
			Message.error({
				message:'服务端异常'
			})
			reject(err.data)
		});
	})
};

export {
    loginreq,
    req,
    upload
}